package com.elong.android.specialhouse.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.elong.android.specialhouse.ApartmentAPI;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.JSONConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.base.BaseVolleyActivity;
import com.elong.android.specialhouse.entity.ApartmentDatepickerParam;
import com.elong.android.specialhouse.entity.response.CalendarInfor;
import com.elong.android.specialhouse.request.GetPriceReq;
import com.elong.android.specialhouse.utils.CalendarUtils;
import com.elong.android.specialhouse.utils.DateTimeUtils;
import com.elong.android.specialhouse.utils.DateTimeUtils.WeekendHolidayBean;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.StringResponse;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;

public class DatePickerActivity extends BaseVolleyActivity<IResponse<?>> implements
             OnClickListener{
	private static final String TAG="DatePickerActivity";
	private static final String RMB = "¥";
	
	private static final int STATE_NORMAL = 1;
	private static final int STATE_TODAY = 2;
	private static final int STATE_DISABLED = 3;
	private static final int STATE_VOID = 4;
	private static final int STATE_CHECKIN = 5;
	private static final int STATE_CHECKOUT = 6;
	private static final int STATE_HOLIDAY = 7;
	private static final int STATE_WEEKEND_HOLIDAY = 8;
	private static final int STATE_LATENIGHT = 9;// 额外带"深夜"字样,显示优先级小于"入住"
	private static final int STATE_BOOK_DISABLED = 10;

	private final static int TAG_STATE = R.id.tag_state;
	private final static int TAG_LATENIGHT = R.id.tag_latenight;
   
	private final static int POSITION_TEXT = 0;
	private final static int POSITION_DAY = 1;
	private final static int POSITION_PRICE = 2;
	
	private ScrollView  mScrollView;
	private FrameLayout mFlCalendar;//日历
	// titleBar
	private TextView mTvInterval;
	
	private int mCellNum;//日期格子总数
	private ApartmentDatepickerParam mDatepickerParam = null;
	private List<WeekendHolidayBean> mWeekendHoliday;// 添加周末及放假日期
	private HashMap<Calendar, String> mHolidaysMap;// 节假日
	private ArrayList<LinearLayout> mCellList = new ArrayList<LinearLayout>();
    
	// 是否第一次点击,用来判断是选入住还是离店日期 
	private boolean isFirstClick = true;
	// 删除入住离店日期
	private Button mBtnCheckInCancel = null;
	private Button mBtnCheckOutCancel = null;
	private LinearLayout mCellToday;
	private LinearLayout mCellLastCheckin;
	private LinearLayout mCellLastCheckout;
	
	// 是否显示价格 
	private boolean isShowPrice = true;
	//价格map
	private	HashMap<String,String> priceMap = new HashMap<String,String>();
	//可租状态map
	private	HashMap<String,Boolean> stateMap = new HashMap<String,Boolean>();
	// 房源Id 
	private Long mHouseId;
	// 最短入住天数
	private int mMinDays;
	// 最长入住天数
	private int mMaxDays;
	// 提前预定天数
	private int mAdvanceDays;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//获取传递过来的参数
		try {
			isShowPrice = getIntent().getBooleanExtra(AppConstants.ACTIVITY_KEY_IS_SHOW_PRICE,
					true);
			//获取房源id
			mHouseId = getIntent().getLongExtra(AppConstants.ACTIVITY_KEY_HOUSE_ID, 0);
			Serializable serializable = getIntent().getSerializableExtra(
					ApartmentDatepickerParam.TAG);
			if (serializable instanceof ApartmentDatepickerParam) {
				mDatepickerParam = (ApartmentDatepickerParam) serializable;
				mMinDays = mDatepickerParam.shortestStay;
				mMaxDays = mDatepickerParam.longestStay;
				mAdvanceDays = mDatepickerParam.checkInEarly;
			} else {
				finish();
			}
		} catch (Exception e) {
			finish();
		}
		if (isMorningTime()) {
			mDatepickerParam.startDate = DateTimeUtils
					.getCurrentDateTimeForMorning();
			tipsMorningView();
		}
		int interval = DateTimeUtils.getIntervalDays(
				mDatepickerParam.checkInDate, mDatepickerParam.checkOutDate);
		mTvInterval.setText(String.format(getString(R.string.select_days),interval));
		mHolidaysMap = DateTimeUtils.genHolidays();
		mWeekendHoliday = DateTimeUtils.genWeekendHolidays();
		showLoading();
		//创建日历
		new Thread() {
			public void run() {
				final LinearLayout root = createCalendar();
				runOnUiThread(new Runnable(){
					@Override
					public void run() {
						//更新UI
						mFlCalendar.addView(root);
						dismissAllDialog();
						if(isShowPrice){
							//获取价格信息
							requestCalendarPrice();
						}
					}
				});
			}
		}.start();
	}

	@Override
	protected void initContentView() {
		setContentView(R.layout.act_datepicker);
    	mScrollView=(ScrollView) findViewById(R.id.scrollView);
		mFlCalendar = (FrameLayout) findViewById(R.id.flCalendar);
		mTvInterval = (TextView) findViewById(R.id.common_head_title);
		// 初始化删除按钮
		mBtnCheckInCancel = new Button(this);
		mBtnCheckInCancel.setBackgroundResource(R.drawable.date_widget_cancel);
		mBtnCheckInCancel.setOnClickListener(this);
		mBtnCheckOutCancel = new Button(this);
		mBtnCheckOutCancel.setBackgroundResource(R.drawable.date_widget_cancel);
		mBtnCheckOutCancel.setOnClickListener(this);
	}

	/** 
	 * 创建日历
	 */
	private LinearLayout createCalendar() {
    	LinearLayout root = new LinearLayout(this);
		root.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		root.setOrientation(LinearLayout.VERTICAL);
		root.setBackgroundColor(0xf7f7f7);
		root.setPadding(10, 0, 10, 10);
		Calendar cursor = (Calendar) mDatepickerParam.startDate.clone();
		int numberOfdisabledDays = cursor.get(Calendar.DAY_OF_MONTH) - 1;//开始时间是今天，是几号减去一就有几天不能选
		cursor.set(Calendar.DAY_OF_MONTH, 1);//cursor从本月1号开始
		Calendar farthestDay = (Calendar) mDatepickerParam.startDate.clone();
		farthestDay.add(Calendar.DAY_OF_MONTH, mDatepickerParam.dateRange - 1);//最大显示的日期是开始时间加上间隔减去一
		
		// 日期格子总数=间隔+当月已过去的天数+最后一个月超期的天数
		mCellNum = mDatepickerParam.dateRange + numberOfdisabledDays;
		mCellNum +=farthestDay.getActualMaximum(Calendar.DAY_OF_MONTH)-farthestDay.get(Calendar.DAY_OF_MONTH);
		
		LinearLayout weekLine = null;
		int maxNumberOfDaysCurrentMonth = 0;

		for (int i = 0; i < mCellNum; i++) {
			if (cursor.get(Calendar.DAY_OF_MONTH) == 1) {	
				if (weekLine != null) {
					root.addView(weekLine);
				}
				weekLine = generateOneWeek();//新建一周
				maxNumberOfDaysCurrentMonth = cursor
						.getActualMaximum(Calendar.DAY_OF_MONTH);
				LinearLayout calendarHead = (LinearLayout) View.inflate(this,
						R.layout.header_datepicker_calendar, null);
				root.addView(calendarHead, LayoutParams.MATCH_PARENT,
						LayoutParams.WRAP_CONTENT);
				setCalendarHead(calendarHead, cursor);
				int voidSpaceNum = cursor.get(Calendar.DAY_OF_WEEK) - 1;
				for (int j = 0; j < voidSpaceNum; j++) {
					LinearLayout cell = (LinearLayout) weekLine.getChildAt(j);
					setState(cell, STATE_VOID, "");
					cell.setTag(TAG_STATE, STATE_VOID);
				}
			} else if (cursor.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
				if (weekLine != null) {
					root.addView(weekLine);
				}
				weekLine = generateOneWeek();
			}
			if (cursor.get(Calendar.DAY_OF_MONTH) == maxNumberOfDaysCurrentMonth) {
				int voidSpaceNum = 7 - cursor.get(Calendar.DAY_OF_WEEK);
				for (int j = 0; j < voidSpaceNum; j++) {
					LinearLayout cell = (LinearLayout) weekLine
							.getChildAt(cursor.get(Calendar.DAY_OF_WEEK) + j);
					setState(cell, STATE_VOID, "");
					cell.setTag(TAG_STATE, STATE_VOID);
				}
			}
			
			LinearLayout cell = (LinearLayout) weekLine.getChildAt(cursor
					.get(Calendar.DAY_OF_WEEK) - 1);
			TextView day = (TextView) cell.getChildAt(POSITION_DAY);
			// 设置格子日期
			day.setText(String.valueOf(cursor.get(Calendar.DAY_OF_MONTH)));
			cell.setTag(cursor.getTimeInMillis());//用来获取点击的日期
			cell.setId(i + 1);//设置ID用来findview			
			setState(cell, STATE_NORMAL, "");
			cell.setTag(TAG_STATE, STATE_NORMAL);
			// 遍历节假日
			Iterator<Entry<Calendar, String>> iter = mHolidaysMap.entrySet().iterator();
			while (iter.hasNext()) {
				Entry<Calendar, String> entry = (Entry<Calendar, String>) iter.next();
				Calendar key = entry.getKey();
				String str = entry.getValue();
				if (DateTimeUtils.compareCalendar(cursor, key) == 0) {
						setState(cell, STATE_HOLIDAY, str);
						cell.setTag(TAG_STATE, STATE_HOLIDAY);
				}
			}
			// 遍历周六日及放假日期
			int dayOfWeek = cursor.get(Calendar.DAY_OF_WEEK);
			if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
				setState(cell, STATE_WEEKEND_HOLIDAY, "");
				cell.setTag(TAG_STATE, STATE_WEEKEND_HOLIDAY);
			}
			for (int j = 0; j < mWeekendHoliday.size(); j++) {
				WeekendHolidayBean bean = mWeekendHoliday.get(j);
				Calendar key = bean.getKey();
				if (DateTimeUtils.compareCalendar(cursor, key) == 0) {
					if (bean.isHoliday()) {
						setState(cell, STATE_WEEKEND_HOLIDAY, "");
						cell.setTag(TAG_STATE, STATE_WEEKEND_HOLIDAY);
						break;
					} else {
						setState(cell, STATE_NORMAL, "");
						cell.setTag(TAG_STATE, STATE_NORMAL);
					}
				}
			}
			if (DateTimeUtils.compareCalendar(cursor, mDatepickerParam.startDate) == -1) {
				// 禁用过期日子
				setState(cell, STATE_DISABLED, "");
				cell.setTag(TAG_STATE, STATE_DISABLED);
			} else if (DateTimeUtils.compareCalendar(cursor, mDatepickerParam.checkInDate) != -1
					&& DateTimeUtils.compareCalendar(cursor, mDatepickerParam.checkOutDate) != 1) {
				setState(cell, STATE_NORMAL, "");
				cell.setSelected(true);
			} else if (DateTimeUtils.compareCalendar(cursor, farthestDay) == 1) {
				// 禁用超期日子
				setState(cell, STATE_DISABLED, "");
				cell.setTag(TAG_STATE, STATE_DISABLED);
			}
			// 初始化日历时的"深夜"特殊判断
			Calendar c = (Calendar) mDatepickerParam.startDate.clone();
			c.add(Calendar.DAY_OF_MONTH, 1);
			if (DateTimeUtils.compareCalendar(cursor, mDatepickerParam.startDate) == 0
					&& DateTimeUtils.compareCalendar(c, DateTimeUtils.getCurrentDateTime()) == 0) {
				setState(cell, STATE_LATENIGHT, "");
				cell.setTag(TAG_LATENIGHT, STATE_LATENIGHT);
			}
			if (DateTimeUtils.compareCalendar(cursor, CalendarUtils.getCalendarInstance()) == 0) {
				setState(cell, STATE_TODAY, "");
				cell.setTag(TAG_STATE, STATE_TODAY);
			}
			if (DateTimeUtils.compareCalendar(cursor, mDatepickerParam.checkInDate) == 0) {
				setState(cell, STATE_CHECKIN, "");
			}
			if (DateTimeUtils.compareCalendar(cursor, mDatepickerParam.checkOutDate) == 0) {
				setState(cell, STATE_CHECKOUT, "");
			}
			cursor.add(Calendar.DAY_OF_MONTH, 1);
		}
		if (weekLine != null) {
			root.addView(weekLine);
		}
		return root;
    }

	/** 
	 * 判断是否属于24:00~6:00是凌晨时间段
	 * @return boolean
	 */
	private boolean isMorningTime() {
		return CalendarUtils.getCalendarInstance().get(Calendar.HOUR_OF_DAY) < 5;
	}
	/** 
	 * 凌晨时间段，显示选择入住日期提示
	 */
	private void tipsMorningView() {
		TextView mormingInfo = (TextView) findViewById(R.id.morning_info);
		Calendar trueDate = CalendarUtils.getCalendarInstance();
		Calendar temp = (Calendar) trueDate.clone();
		temp.add(Calendar.HOUR_OF_DAY, -6);
		mormingInfo.setVisibility(View.VISIBLE);
		mormingInfo.setText(trueDate.get(Calendar.DATE) + getString(R.string.morning_tip)
				+ temp.get(Calendar.DATE) + getString(R.string.morning_tip2));
	}
	/** 
	 * 设置日期格子状态
	 * @param cell 日期格子
	 * @param state 状态：今天|入住|离店|不可点击...
	 * @param holiday 节日
	 */
	@SuppressWarnings("deprecation")
	private void setState(LinearLayout cell, int state, String holiday) {
		TextView text = (TextView) cell.getChildAt(POSITION_TEXT);//标示
		TextView day = (TextView) cell.getChildAt(POSITION_DAY);//日期
		TextView price = (TextView) cell.getChildAt(POSITION_PRICE);//价格

		cell.setBackgroundColor(AppConstants.COLOR_WHITE);
		day.setBackgroundDrawable(CalendarUtils.createBGSelector(AppConstants.COLOR_WHITE, AppConstants.COLOR_ORANGE));
		switch (state) {
		case STATE_NORMAL:
			day.setTextColor(CalendarUtils.createTextSelector(AppConstants.COLOR_BLACK, AppConstants.COLOR_WHITE));
			price.setTextColor(AppConstants.COLOR_BLACK);
//			price.setTextColor(createTextSelector(0xff333333, 0xffffffff));
			text.setVisibility(View.INVISIBLE);
			break;
		case STATE_CHECKIN:
			day.setTextColor(CalendarUtils.createTextSelector(AppConstants.COLOR_BLACK, AppConstants.COLOR_WHITE));
			price.setTextColor(AppConstants.COLOR_BLACK);
			text.setTextColor(AppConstants.COLOR_BLACK);
//			price.setTextColor(createTextSelector(0xff333333, 0xffffffff));
//			text.setTextColor(createTextSelector(0xff333333, 0xffffffff));
			text.setVisibility(View.VISIBLE);
			text.setText(getString(R.string.checkin));
			mCellLastCheckin = cell;
			break;
		case STATE_CHECKOUT:
			day.setTextColor(CalendarUtils.createTextSelector(AppConstants.COLOR_BLACK, AppConstants.COLOR_WHITE));
			price.setTextColor(AppConstants.COLOR_BLACK);
			text.setTextColor(AppConstants.COLOR_BLACK);
//			price.setTextColor(createTextSelector(0xff333333, 0xffffffff));
//			text.setTextColor(createTextSelector(0xff333333, 0xffffffff));
			text.setVisibility(View.VISIBLE);
			text.setText(getString(R.string.checkout));
			mCellLastCheckout = cell;
			break;
		case STATE_TODAY:
			day.setTextColor(CalendarUtils.createTextSelector(AppConstants.COLOR_TODAY, AppConstants.COLOR_WHITE));
			price.setTextColor(CalendarUtils.createTextSelector(AppConstants.COLOR_TODAY, AppConstants.COLOR_WHITE));
			text.setTextColor(CalendarUtils.createTextSelector(AppConstants.COLOR_TODAY, AppConstants.COLOR_WHITE));
			text.setVisibility(View.VISIBLE);
			text.setText(getString(R.string.today));
			mCellToday = cell;
			break;
		case STATE_HOLIDAY:
			day.setTextColor(CalendarUtils.createTextSelector(AppConstants.COLOR_BLACK, AppConstants.COLOR_WHITE));
			day.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
			day.setText(holiday);
			price.setTextColor(AppConstants.COLOR_BLACK);
			text.setVisibility(View.INVISIBLE);
			break;
		case STATE_WEEKEND_HOLIDAY:
			day.setTextColor(AppConstants.COLOR_GREEN);
			price.setTextColor(AppConstants.COLOR_BLACK);
			text.setVisibility(View.INVISIBLE);
			break;
		case STATE_DISABLED:
			cell.setBackgroundColor(AppConstants.COLOR_WHITE);
			day.setTextColor(AppConstants.COLOR_DISABLE_TEXT);
			text.setVisibility(View.INVISIBLE);
			price.setVisibility(View.INVISIBLE);
			cell.setEnabled(false);
			break;
		case STATE_VOID:
			cell.setBackgroundColor(AppConstants.COLOR_WHITE);
			day.setVisibility(View.GONE);
			text.setVisibility(View.GONE);
			price.setVisibility(View.GONE);
			cell.setEnabled(false);
			break;
		case STATE_LATENIGHT:
			day.setTextColor(CalendarUtils.createTextSelector(AppConstants.COLOR_BLACK, AppConstants.COLOR_WHITE));
			price.setTextColor(AppConstants.COLOR_BLACK);
			text.setTextColor(AppConstants.COLOR_BLACK);
			text.setText(getString(R.string.latenight));
			text.setVisibility(View.VISIBLE);
			break;
		case STATE_BOOK_DISABLED:
			cell.setBackgroundColor(AppConstants.COLOR_WHITE);
			day.setBackgroundColor(AppConstants.COLOR_WHITE);
			day.setTextColor(AppConstants.COLOR_DISABLE_TEXT);
			price.setTextColor(AppConstants.COLOR_DISABLE_TEXT);
			text.setVisibility(View.INVISIBLE);
			break;
		}
	}
	/**
	 * @return 生成一周的日期格子(一行)
	 */
	private LinearLayout generateOneWeek() {
		LinearLayout week = new LinearLayout(this);
		LayoutParams lpWeek = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		week.setLayoutParams(lpWeek);
		week.setBackgroundColor(0xffcccccc);
//		week.setPadding(0, 0, px(1), 0);
		for (int i = 0; i < 7; i++) {
			LinearLayout llCell = new LinearLayout(this);
			LayoutParams lpCell = new LayoutParams(LayoutParams.MATCH_PARENT, px(50), 1);
//			lpCell.setMargins(1, 1, 0, 0);
			llCell.setOrientation(LinearLayout.VERTICAL);
			llCell.setLayoutParams(lpCell);
			llCell.addStatesFromChildren();
			llCell.setGravity(Gravity.CENTER_HORIZONTAL);
			llCell.setOnClickListener(this);
			
			LayoutParams lpText = new LayoutParams(LayoutParams.WRAP_CONTENT, 0, 0.8f);
			TextView text = new TextView(this);
			text.setLayoutParams(lpText);
			text.setTextColor(Color.BLACK);
			text.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
			text.setGravity(Gravity.CENTER);
			llCell.addView(text, POSITION_TEXT);
			
			TextView day = new TextView(this);
			LayoutParams lpDay = new LayoutParams(LayoutParams.MATCH_PARENT, 0, 1);
			day.setLayoutParams(lpDay);
			day.getPaint().setFakeBoldText(true);
			day.setTextColor(Color.BLACK);
			day.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
			day.setGravity(Gravity.CENTER);
			llCell.addView(day, POSITION_DAY);

			TextView price = new TextView(this);
			LayoutParams lpPrice = new LayoutParams(LayoutParams.WRAP_CONTENT, 0, 0.8f);
			price.setLayoutParams(lpPrice);
			price.setTextColor(Color.BLACK);
			price.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
			price.setGravity(Gravity.CENTER);
			llCell.addView(price, POSITION_PRICE);
			
			week.addView(llCell, i);
			// 记录每一个Cell的信息
			mCellList.add(llCell);
		}
		return week;
	}
	private int px(float dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}
	/** 
	 * 设置日历title显示年月
	 * @param calendarHead
	 * @param c 
	 */
	private void setCalendarHead(LinearLayout calendarHead, Calendar c) {
		TextView txYear = (TextView) calendarHead.findViewById(R.id.tvYear);
		TextView tvMonth = (TextView) calendarHead.findViewById(R.id.tvMonth);
		txYear.setText(Integer.toString(c.get(Calendar.YEAR)));
		tvMonth.setText(Integer.toString(c.get(Calendar.MONTH) + 1));
	}

	@Override
	public void onClick(View v) {
		 super.onClick(v);
		 if (v.getTag() != null) {
			Calendar clicked = CalendarUtils.getCalendarInstance();
			clicked.setTimeInMillis((Long) v.getTag());
			LinearLayout clickedCell = (LinearLayout) v;
			//第一次点击，选择入住日期
			if (isFirstClick) {
				Calendar lastDay = (Calendar) this.mDatepickerParam.startDate.clone();
				lastDay.add(Calendar.DAY_OF_MONTH,mDatepickerParam.dateRange - 1);
				if (DateTimeUtils.compareCalendar(clicked, lastDay) == 0) {
					mDatepickerParam.checkInDate = clicked;
					Calendar beyondLastDay = (Calendar) clicked.clone();
					beyondLastDay.add(Calendar.DAY_OF_MONTH, 1);
					mDatepickerParam.checkOutDate = beyondLastDay;
					showTopToast(getString(R.string.lastday_tip));
					onBackPressed();
					return;
				}
				//不可租状态不能选为入住
				if (clickedCell.getTag(TAG_STATE) != null
						&& (Integer) (clickedCell
								.getTag(TAG_STATE)) == STATE_BOOK_DISABLED) {
					return;
				}
				//判断入住日期和当前日期的间隔是否符合提前预定规则
				if(DateTimeUtils.getIntervalDays(
						clicked, CalendarUtils.getCalendarInstance()) < mAdvanceDays){
					showTopToast(String.format(getString(R.string.advance_book_tip),mAdvanceDays));
					return;
				}
				mDatepickerParam.checkInDate = clicked;
				mTvInterval.setText(R.string.hotel_select_checkout);

				isFirstClick = false;
				if (mCellLastCheckin != null) {
					Object o = mCellLastCheckin.getTag(TAG_STATE);
					setState(mCellLastCheckin, o == null ? STATE_NORMAL
							: (Integer) o, "");
					if (mCellLastCheckin.getTag(TAG_LATENIGHT) != null
							&& (Integer) (mCellLastCheckin
									.getTag(TAG_LATENIGHT)) == STATE_LATENIGHT) {
						setState(mCellLastCheckin, STATE_LATENIGHT, "");
					}
				}
				if (mCellLastCheckout != null) {
					Object o = mCellLastCheckout.getTag(TAG_STATE);
					setState(mCellLastCheckout, o == null ? STATE_NORMAL
							: (Integer) o, "");
				}
				if (mCellToday != null) {
					setState(mCellToday, STATE_TODAY, "");
				}
				setState(clickedCell, STATE_CHECKIN, "");
				FrameLayout.LayoutParams fl = new FrameLayout.LayoutParams(
						clickedCell.getHeight() / 3,
						clickedCell.getHeight() / 3, Gravity.TOP
								| Gravity.LEFT);
				fl.setMargins(clickedCell.getRight()- clickedCell.getWidth() / 5,
						((View) clickedCell.getParent()).getTop()
								- clickedCell.getHeight() / 5, 0, 0);
				mBtnCheckInCancel.setLayoutParams(fl);
				mFlCalendar.addView(mBtnCheckInCancel, fl);
				clickedCell.setSelected(true);
				//点击的格子设置为入住，其余格子恢复初始状态
				for (int i = 1; i <= mCellNum; i++) {
					LinearLayout cell = (LinearLayout) mFlCalendar.findViewById(i);
					Calendar c = CalendarUtils.getCalendarInstance();
					c.setTimeInMillis((Long) cell.getTag());
					if (DateTimeUtils.compareCalendar(c, mDatepickerParam.checkInDate) != 0) {
						cell.setSelected(false);
						Object o = cell.getTag(TAG_STATE);
						setState(cell, o == null ? STATE_NORMAL: (Integer) o, "");
						if (cell.getTag(TAG_LATENIGHT) != null
								&& (Integer) (cell.getTag(TAG_LATENIGHT)) == STATE_LATENIGHT) {
							setState(cell, STATE_LATENIGHT, "");
						}
					}
				}
			}
			//第二次点击
			else{
//				// 判断入离店日期，是否超过90天
//				if (exceed90Days(datepickerParam.checkInDate, clicked)) {
//					showTopToast(getString(R.string.tip_exceed_90));
//					return;
//				}
				if (hasView(mFlCalendar, mBtnCheckInCancel)
							&& DateTimeUtils.compareCalendar(clicked, mDatepickerParam.checkInDate) == 0) {
					 //取消入住
					 performCheckInCancel(clickedCell);
					 return;
				} else{
					  if (DateTimeUtils.compareCalendar(clicked, mDatepickerParam.checkInDate) == -1) {
						  //如果离店日期比入店时期早，则把离店日期设为入店时期
						  //不可租状态不能选为入住
						  if (clickedCell.getTag(TAG_STATE) != null
									&& (Integer) (clickedCell
											.getTag(TAG_STATE)) == STATE_BOOK_DISABLED) {
								return;
						  }
						  //判断入住日期和当前日期的间隔是否符合提前预定规则
						  if(DateTimeUtils.getIntervalDays(
								  clicked, CalendarUtils.getCalendarInstance()) < mAdvanceDays){
							  showTopToast(String.format(getString(R.string.advance_book_tip),mAdvanceDays));
							  return;
						  }
							// 第一步，将之前的入店日期取消
							if (mCellLastCheckin != null) {
								Object o = mCellLastCheckin.getTag(TAG_STATE);
								setState(mCellLastCheckin, o == null ? STATE_NORMAL : (Integer) o, "");
								if (mCellLastCheckin.getTag(TAG_LATENIGHT) != null
										&& (Integer) (mCellLastCheckin
												.getTag(TAG_LATENIGHT)) == STATE_LATENIGHT) {
									setState(mCellLastCheckin, STATE_LATENIGHT, "");
								}
							}

							performCheckInCancel(mCellLastCheckin);
							
							// 第二步：设置最新的入店时期
							setState(clickedCell, STATE_CHECKIN, "");
							mDatepickerParam.checkInDate = clicked;
							clickedCell.setSelected(true);
							isFirstClick = false;
							mTvInterval.setText(R.string.hotel_select_checkout);
							FrameLayout.LayoutParams fl = new FrameLayout.LayoutParams(
									clickedCell.getHeight() / 3,
									clickedCell.getHeight() / 3, Gravity.TOP
											| Gravity.LEFT);
							fl.setMargins(clickedCell.getRight()- clickedCell.getWidth() / 5,
									((View) clickedCell.getParent()).getTop()
											- clickedCell.getHeight() / 5, 0, 0);
							mBtnCheckInCancel.setLayoutParams(fl);
							mFlCalendar.addView(mBtnCheckInCancel, fl);
					  }
					  else{
						  //设置离店日期
						  if(checkIfBookDisabled(mDatepickerParam.checkInDate,clicked)){
						    	showTopToast(getString(R.string.enabled_tip));
						    	return;
						  }
						  //判断最短入住
						  if(DateTimeUtils.getIntervalDays(
								  mDatepickerParam.checkInDate, clicked) < mMinDays){
							  showTopToast(String.format(getString(R.string.mindays_book_tip), mMinDays));
							  return;
						  }
						  //判断最长入住
						  if(DateTimeUtils.getIntervalDays(
								  mDatepickerParam.checkInDate, clicked) > mMaxDays){
							  showTopToast(String.format(getString(R.string.maxdays_book_tip), mMaxDays));
							  return;
						  }
						  setState(clickedCell, STATE_CHECKOUT, "");
						  mDatepickerParam.checkOutDate = clicked;
						  int interval = DateTimeUtils.getIntervalDays(
								  mDatepickerParam.checkInDate,
								  mDatepickerParam.checkOutDate);
						  mTvInterval.setText(String.format(getString(R.string.select_days),interval));
						  isFirstClick = true;
						  FrameLayout.LayoutParams fl = new FrameLayout.LayoutParams(
									clickedCell.getHeight() / 3,
									clickedCell.getHeight() / 3, Gravity.TOP
											| Gravity.LEFT);
						  fl.setMargins(clickedCell.getRight()- clickedCell.getWidth() / 5,
									((View) clickedCell.getParent()).getTop()
											- clickedCell.getHeight() / 5, 0, 0);
						  mBtnCheckOutCancel.setLayoutParams(fl);
						  mFlCalendar.addView(mBtnCheckOutCancel, fl);
						  for (int i = 1; i <= mCellNum; i++) {
								LinearLayout cell = (LinearLayout) mFlCalendar
										.findViewById(i);
								Calendar c = CalendarUtils.getCalendarInstance();
								c.setTimeInMillis((Long) cell.getTag());
								if (mDatepickerParam.checkOutDate != null
										&& DateTimeUtils.compareCalendar(c,
										mDatepickerParam.checkInDate) != -1
										&& DateTimeUtils.compareCalendar(c,
										mDatepickerParam.checkOutDate) != 1
										&& (Integer) cell.getTag(TAG_STATE)!=STATE_DISABLED
										|| v.getId() == cell.getId()) {
									cell.setSelected(true);
								} else {
									cell.setSelected(false);
								}
						  }
						  //返回
						  onBackPressed();
					  }
				 }
			}
		}else if (v.equals(mBtnCheckInCancel)) {
			for (int i = 1; i <= mCellNum; i++) {
				LinearLayout cell = (LinearLayout) mFlCalendar.findViewById(i);
				Calendar c = CalendarUtils.getCalendarInstance();
				c.setTimeInMillis((Long) cell.getTag());
				if (mDatepickerParam.checkInDate != null
						&& DateTimeUtils.compareCalendar(c, mDatepickerParam.checkInDate) == 0) {
					performCheckInCancel(cell);
				}
			}
		} else if (v.equals(mBtnCheckOutCancel)) {
			for (int i = 1; i <= mCellNum; i++) {
				LinearLayout cell = (LinearLayout) mFlCalendar.findViewById(i);
				Calendar c = CalendarUtils.getCalendarInstance();
				c.setTimeInMillis((Long) cell.getTag());
				if (mDatepickerParam.checkOutDate != null
						&& DateTimeUtils.compareCalendar(c, mDatepickerParam.checkOutDate) == 0) {
//					performCheckOutCancel(cell);
				}
			}
		}
		
	}
	/** 
	 * 检查入住区间是否包含不可租的日期,返回true表示包含
	 * @param checkInDate 入住日期
	 * @param checkOutDate 离店日期
	 */
	private boolean checkIfBookDisabled(Calendar checkInDate, Calendar checkOutDate) {
		if(stateMap.isEmpty()){
			return false;
		}
		Calendar checkInDateTemp = (Calendar) checkInDate.clone();
		SimpleDateFormat fomatter=new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());

		checkInDateTemp.add(Calendar.DAY_OF_YEAR, 1);  //加1天
		while(checkInDateTemp.compareTo(checkOutDate) == -1) { 
			String date = fomatter.format(new Date(checkInDateTemp.getTimeInMillis()));
			if(stateMap.get(date)!=null
					&& !stateMap.get(date)){
				//区间内有一天是不可租的，结束循环
				return true;
			}
			checkInDateTemp.add(Calendar.DAY_OF_YEAR, 1);  //加1天			   
		}
		return false;
		
	}

	private boolean hasView(ViewGroup parent, View child) {
		for (int i = 0; i < parent.getChildCount(); i++) {
			if (parent.getChildAt(i).equals(child)) {
				return true;
			}
		}
		return false;
	}
	/**
	 * 删除入住
	 */
	private void performCheckInCancel(LinearLayout clickedCell) {
		isFirstClick = true;
		Object o = clickedCell.getTag(TAG_STATE);
		setState(clickedCell, o == null ? STATE_NORMAL : (Integer) o, "");
		if (clickedCell.getTag(TAG_LATENIGHT) != null
				&& (Integer) (clickedCell.getTag(TAG_LATENIGHT)) == STATE_LATENIGHT) {
			setState(clickedCell, STATE_LATENIGHT, "");
		}
		mFlCalendar.removeView(mBtnCheckInCancel);
		clickedCell.setSelected(false);
		mTvInterval.setText(R.string.hotel_select_checkin);
	}

	private void showTopToast(String s) {
		Toast t = Toast.makeText(this, s, Toast.LENGTH_SHORT);
		t.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, this
				.getResources().getDisplayMetrics().heightPixels / 4);
		t.show();
	}
	
	/** 
	 * 向服务器请求获取价格日历信息 
	 */
	private void requestCalendarPrice() {
		GetPriceReq req = new GetPriceReq();
		req.HouseId = mHouseId;
//		req.HouseId = 100000;//房源id，测试用
		requestHttp(req, ApartmentAPI.getTenantCalendar, StringResponse.class);
	}
	
	@Override
	public void onTaskPost(ElongRequest request, IResponse<?> t) {
		super.onTaskPost(request, t);
		
		JSONObject result = (JSONObject) JSONObject.parse(((StringResponse) t).getContent());
		if(handleIsError(request, result)){
		   return;
		}
			JSONArray arrayResult = result.getJSONArray(JSONConstants.ATTR_CALENDAR);
			if (null == arrayResult ) {
	            return ;
			}else {
	        	List<CalendarInfor> calendarInfor = new ArrayList<CalendarInfor>();
	        	for(int i=0;i<arrayResult.size();i++){
//	        		JSONArray indexResult = arrayResult.getJSONArray(i);
//	        		for(int j=0;j<indexResult.size();j++){
//	        		    CalendarInfor parseResult=JSON.parseObject(indexResult.get(j).toString(), CalendarInfor.class);
//	        		    calendarInfor.add(parseResult);
//	        		}
	        		CalendarInfor parseResult= JSON.parseObject(arrayResult.get(i).toString(), CalendarInfor.class);
	    		    calendarInfor.add(parseResult);
	        	}     
	        	showPrice(calendarInfor);
	        }
		
	}
	
	/** 
	 * 将服务器返回的价格信息展示在界面上
	 * @param calendarInfor 解析结果
	 */
	private void showPrice(List<CalendarInfor> calendarInfor) {

		for(CalendarInfor info:calendarInfor){
			priceMap.put(info.getCalendarTime().substring(0, 10), info.getBasePrice());
			stateMap.put(info.getCalendarTime().substring(0, 10), info.getState());
		}
		SimpleDateFormat fomatter=new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());
	    for (int i = 1; i <= mCellNum; i++) {
			LinearLayout cell = (LinearLayout) mFlCalendar.findViewById(i);
			String date = fomatter.format(new Date((Long) cell.getTag()));
			//标记为不可租
			if(stateMap.get(date)!=null
			      &&!stateMap.get(date)){
				Calendar clicked = CalendarUtils.getCalendarInstance();
				clicked.setTimeInMillis((Long) cell.getTag());			
				if (mDatepickerParam.checkOutDate != null
						&& DateTimeUtils.compareCalendar(clicked, mDatepickerParam.checkOutDate) == 0) {
					//如果是离店日期则显示为离店状态					
					setState(cell, STATE_CHECKOUT, "");
				}else{
					//否则是不可租状态
					setState(cell, STATE_BOOK_DISABLED, "");
				}		
				cell.setTag(TAG_STATE, STATE_BOOK_DISABLED);              
			}
			
			//标记价格			
			if(priceMap.get(date)!=null
					&&!priceMap.get(date).equals("")){
				TextView tv=(TextView) cell.getChildAt(POSITION_PRICE);
				tv.setText(RMB+priceMap.get(date));
			}
			
	    }		
	}

	@Override
	public void onBackPressed() {
		//选择好入住和离店时间后执行返回
		this.setResult(
				RESULT_OK,
				getIntent().putExtra(ApartmentDatepickerParam.TAG,
						mDatepickerParam));
		super.back();
	}
	@Override
	protected void onDestroy() {
		mCellList.clear();
		mCellList = null;
		mScrollView.removeAllViews();
		super.onDestroy();
	}
}
